# -*- coding:utf-8 -*-
"""
关键价格突破交易
"""
from function.interface import *


class Strategy1(JyInterface):
    symbol = "BTC/USDT"
    pricelimit  = 8814
    pricelimit2 = 9000
    side = "buy"
    amount = 0.01
    period = '2sec'
    
    def __init__(self, **kwargs):
        super(Strategy1,self).__init__(**kwargs)
        self.flag = 0     
        
    def loop(self):
        """策略部分"""
        lastprice = self.getLastPrice(self.symbol) # 获取最新价
        tick      = self.getJumpPrice(self.symbol)  # 获取跳价
        if self.flag == 0:
            if self.side == "buy": # 买入
                usdt = self.getSecondary(self.symbol) # 获取二级货币
                if lastprice >= self.pricelimit and usdt >= self.pricelimit*self.amount: # 最新价大于限价
                    orderId = self.buy(self.symbol, self.pricelimit + tick*3, self.amount)
                    self.flag = 1
            else:
                position = self.getPosition(self.symbol) # 往下突破，获取账户持仓
                if lastprice <= self.pricelimit and position >= self.amount:
                    orderId = self.sell(self.symbol, self.pricelimit - tick*3, self.amount)
                    self.flag = 1
        if self.flag == 1:
            if self.side == "buy": # 买入
                position = self.getPositionSt(self.symbol) # 获取策略的持仓
                if lastprice >= self.pricelimit2 and position > 0: # 最新价大于限价
                    orderId = self.sell(self.symbol, self.pricelimit2 - tick*3, position)
                    self.flag = -1
            else:
                usdt = self.getSecondary(self.symbol)
                if lastprice <= self.pricelimit2 and usdt >= self.pricelimit2*self.amount:
                    orderId = self.buy(self.symbol, self.pricelimit2 + tick*3, self.amount)
                    self.flag = -1
                          
            
if __name__ == "__main__":
    st = Strategy1(type_=1, futureOrSpot=0, appKey='e1165f7b8857d0-78937',secret='bf36b9-c08f5',passphrase='',transferId='M_1',grpcAddress="18.136.163.117:9309")
    st.run(st.loop)